(function ($) {

  var URL = {
    GET_TREE: 'json/tree.json',
    GET_FILE: 'json/file.json',
    GET_RIGHT: 'json/right.json'
  };

  var loadingHtml = '<div class="spinner"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>';
  var miniLoadingHtml = '<div class="spinner mini"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>';

  /**
   * 生成树结构
   * @param target -- 目标 <ul class="collapsible collapsible-accordion">
   * @param data -- 树结构数据, 格式如下:
   *    [
   *     {
   *      id: 该节点ID,
   *      label: 该节点显示的文字
   *      isLeaf: 是否为叶子
   *     },...
   *    ]
   */
  function generateTree(target, data) {
    if (!target || !$.isArray(data)) {
      return;
    }

    $(target).empty();
    $.each(data, function (index, item) {
      var $li = $('<li>');
      if (!item.isLeaf) {
        $li.append('<div class="collapsible-header waves-effect no-leaf" data-id="' + item.id + '" data-loaded="0">');
      } else {
        $li.append('<div class="collapsible-header waves-effect leaf" data-id="' + item.id + '">');
      }

      $('<div class="collapsible-text">')
        .append(!item.isLeaf ? '<i class="fa fa-angle-down rotate-icon">' : '')
        .append(item.label + '&nbsp;&nbsp;&nbsp;&nbsp;')
        .appendTo($li);

      if (!item.isLeaf) {
        $('<div class="collapsible-body">')
          .append('<ul class="collapsible collapsible-accordion">')
          .appendTo($li);
      }

      $(target).append($li);
    });
  }

  /**
   * 渲染右边容器内容
   */
  function renderRightContainer(type, data) {
    var _type = type || 0;
    var _data = data || {};

    switch (_type.toString()) {
      case '1':
        renderCards(_data);
        break;

      case '0':
      default:
        $('#main-container').html(_data);
        break;
    }
  }

  function renderCards(data) {
    var shortenText = function (text, length) {
      length = length || 100;
      return text.length > length ? text.slice(0, length) + '...' : text;
    };

    $.each(data, function (index, item) {
      $('<div class="col-md-4 mb-1">').html(
        '<div class="card">' +
        '<div class="card-share">' +
        '<a class="btn-floating btn-action share-toggle primary-color-dark" href="' + item.link + '">' +
        '<i class="fa fa-chevron-right"></i></a>' +
        '</div>' +
        '<div class="card-block">' +
        '<h4 class="card-title">' + item.title + '</h4>' +
        '<hr>' +
        '<p class="card-text">' + shortenText(item.content) + '</p>' +
        '</div>' +
        '</div>'
      ).appendTo($('#main-container'));
    });
  }

  /**
   * 绑定事件
   */
  function bindEvents() {

    // 绑定树中非叶子节点的事件, 加载下一层树节点
    $('#side-nav-tree-root').on('click', '.no-leaf', function (event) {
      if ($(event.target).attr('data-loaded') !== '1') {
        $(event.target).attr('data-loaded', '1');

        // 从后端加载下一层树
        $(event.target).next().next().children('.collapsible.collapsible-accordion').html(miniLoadingHtml);
        $.get({
          url: URL.GET_TREE,
          data: {
            id: $(event.target).attr('data-id')
          }

        }).done(function (response) {
          if (response.status.toString() === '1' && response.data) {
            generateTree(
              $(event.target).next().next().children('.collapsible.collapsible-accordion'),
              response.data
            );
          } else {
            $(event.target).next().next().children('.collapsible.collapsible-accordion').empty();
          }

        }).fail(function () {
          $(event.target).next().next().children('.collapsible.collapsible-accordion').empty();
        });
      }

      if ($(event.target).next().next()[0] &&
        $(event.target).next().next()[0].style &&
        $(event.target).next().next()[0].style.display === 'block') {
        $(event.target).next().next().hide();
      } else {
        $(event.target).next().next().show();
      }
    });

    // 绑定叶子节点事件
    $('#side-nav-tree-root').on('click', '.leaf', function (event) {
      var id = $(event.target).attr('data-id');
      $('#main-container').html('<div class="center-block">' + loadingHtml + '</div>');
      $.get({
        url: URL.GET_FILE,
        data: {
          id: id
        }

      }).done(function (response) {
        if (response.status.toString() === '1' && response.data) {
          renderRightContainer(response.type, response.data);
        } else {
          $('#main-container').empty();
        }

      }).fail(function () {
        $('#main-container').empty();
      });
    });

    // 兼容树的横向长度过长,无法点击的问题
    $('body').on('click', '.collapsible-text', function (event) {
      $(event.target).prev().click();
    });
  }

  function init() {

    // 加载第一层树结构
    $.get({
      url: URL.GET_TREE,
      data: ''
    }).done(function (response) {
      if (response.status.toString() === '1' && response.data) {
        generateTree($('#side-nav-tree-root'), response.data);
      }
    });

    $('#show-date').text( (function () {
      var date = new Date();
      var dayText = '〇一二三四五六日'.split('');
      return date.getFullYear() + '年' + (date.getMonth()+1) + '月' + date.getDate() + '日 星期' + dayText[ date.getDay() ]
    })() );

    // 绑定各种事件
    bindEvents();
  }


  /* -------- 主函数 -------- */

  $(".button-collapse").hide().sideNav('show');

  var el = document.querySelector('.custom-scrollbar');
  Ps.initialize(el);

  init();

})(jQuery);